package com.upload.controller;

import com.upload.constants.UploadDownLoadConstants;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/file")
public class DownLoadController {



    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public String downFile(@RequestParam(value = "name") String fileName, HttpServletResponse response) throws IOException {

        File fileSource = new File(UploadDownLoadConstants.UPLOAD_DIR+fileName);

        if(fileSource.exists()){
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + "test.text");

            byte[] buff = new byte[1024];
            BufferedInputStream bufferedInputStream = null;
            OutputStream outputStream = null;

            try {
                outputStream = response.getOutputStream();
                bufferedInputStream = new BufferedInputStream(new FileInputStream(fileSource));

                int i = bufferedInputStream.read(buff);
                while (i != -1) {
                    outputStream.write(buff, 0, buff.length);
                    outputStream.flush();
                    i = bufferedInputStream.read(buff);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(bufferedInputStream!=null){
                    bufferedInputStream.close();
                }
            }
        }

        return UploadDownLoadConstants.DOWNLOAD_SUCCESS;
    }

}
